package com.flashcash.kotlin.trace

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.text.TextUtils
import com.flashcash.solu.R
import com.flashcash.solu.common.FieldParams
import com.tbruyelle.rxpermissions.RxPermissions
import com.x.leo.apphelper.log.XLog
import com.x.leo.apphelper.utils.BrandUtils
import com.x.leo.apphelper.utils.ErrorHandler
import rx.Subscriber

/**
 * @作者:XLEO
 * @创建日期: 2017/9/4 14:46
 * @描述:上传策略
 *
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 * @下一步：
 */
object TraceManager {
    val REQUEST_PERMISSION_CODE = 0x000AF00
    private val permissionsToCheck: Array<String> by lazy {
        arrayOf(
                Manifest.permission.READ_CONTACTS,
//                Manifest.permission.READ_CALL_LOG,
//                Manifest.permission.READ_SMS,
                Manifest.permission.ACCESS_COARSE_LOCATION,//粗精度定位
                Manifest.permission.ACCESS_FINE_LOCATION,//卫星定位
                Manifest.permission.READ_PHONE_STATE
        )
    }

    fun qualifyPermissions(act: Activity, runnable: Runnable) {
        RxPermissions(act)
                .request(*permissionsToCheck)
//                .map {
//                    it && Collector.contactGranted() && Collector.callLogGranted() && Collector.smsGranted()
//                }
                .subscribe(object : Subscriber<Boolean>() {
                    override fun onError(p0: Throwable?) {
                    }

                    override fun onNext(p0: Boolean?) {
                        if (p0 == true) {
                            runnable.run()
                        } else {
                            val message = StringBuilder(act.getString(R.string.need_permission_to_loan))
                            act.resources.getStringArray(R.array.private_items)?.forEach {
                                message.append(it + ",")
                            }
                            if (TextUtils.equals(message[message.lastIndex].toString(), ','.toString())) {
                                message.replace(message.lastIndex, message.length, "")
                            }
                            ErrorHandler.Builder()
                                    .setCallback(object : ErrorHandler.CallBack {
                                        override fun onAccept() {
                                            toSettingPermissionActivity(act, permissionsToCheck[1])
                                        }

                                        override fun onRefuse() {
                                        }
                                    })
                                    .setContext(act)
                                    .setMessage(message.toString())
                                    .setType(ErrorHandler.HandleType.DIALOG)
                                    .createHandler()?.show()
                        }
                    }

                    override fun onCompleted() {

                    }

                })
    }

    fun toSettingPermissionActivity(act: Activity, permissions: String) {
        try {
            //判断是否为小米系统
            if (TextUtils.equals(BrandUtils.getSystemInfo().os, BrandUtils.SYS_MIUI)) {
                val miuiIntent = Intent("miui.intent.action.APP_PERM_EDITOR")
                miuiIntent.putExtra("extra_pkgname", act.packageName)
                //检测是否有能接受该Intent的Activity存在
                val resolveInfos = act.packageManager.queryIntentActivities(miuiIntent, PackageManager.MATCH_DEFAULT_ONLY)
                if (resolveInfos.size > 0) {
                    act.startActivityForResult(miuiIntent, REQUEST_PERMISSION_CODE)
                    return
                }
            }
            //如果不是小米系统 则打开Android系统的应用设置页
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            val uri = Uri.fromParts("package", act.packageName, null)
            intent.data = uri
            intent.putExtra(FieldParams.GO_SETTING_PERMISSION, permissions)
            act.startActivityForResult(intent, REQUEST_PERMISSION_CODE)
        } catch (e: Throwable) {
            XLog.e("to setting permission activity error:", e, 100)
        }
    }
}

enum class PermissionState {
    //may request again
    //stop request and  buildChannel
    //stop request and never buildChannel
    UNKNOW,
    GRANTED, REFUSED
}
